package top.carrotguo.weibo.retrofit;

import java.sql.BatchUpdateException;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitUtil {
    private static final String BASE_URL = "https://api.weibo.com/2/";
    /*超时时间*/
    private static final int TIME_OUT = 60;
    private static volatile RetrofitUtil mInstance;
    private static Retrofit mRetrofit;

    /**
     * 获取Retrofit工具类的单例模式
     * @return
     */
    public static RetrofitUtil getInstance(){
        if (mInstance == null) {
            synchronized (RetrofitUtil.class){
                if (mInstance == null) {
                    mInstance = new RetrofitUtil();
                }
            }
        }
        return mInstance;
    }

    private RetrofitUtil(){
        initRetrofit();
    }

    /**
     * 初始化retrofit
     */
    private void initRetrofit(){
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.readTimeout(TIME_OUT,TimeUnit.SECONDS);
        builder.writeTimeout(TIME_OUT,TimeUnit.SECONDS);
        builder.connectTimeout(TIME_OUT,TimeUnit.SECONDS);
        OkHttpClient client = builder.build();
        mRetrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    /**
     * 动态生成方法
     * @param cls
     * @param <T>
     * @return
     */
    public <T> T create(Class<T> cls){
        return mRetrofit.create(cls);
    }

}
